<?php
	include("admin-commons.php");
	
	$user = $_COOKIE['user'];
	$hash = $_COOKIE['hash'];
	if(strlen($user) == 0 || strlen($hash) != 32) {
		echo "<html>\n";
		echo "<h2>You must be logged in to view this page, you have been reported.</h2>\n";
		echo "</html>\n";
		die();
	}	
	
	/* Begin Page */
	$removeUser = $_POST['removeUser'];
	
	pageHeader();
	adminNavigation();
	contentHeader();
	echo "<h2> Account Management </h2></br>\n";
	if (strlen($removeUser) == 0)
		getUser();
	else
		removeUser($removeUser);
	contentFooter("You are logged in as ".$user);
	
	/* FUNKtions */
	
	function getUser() {
		$sqlConnection = connectToDatabase();
		mysql_select_db("hpberry", $sqlConnection);
		$userQuery = 'SELECT * FROM accounts';
		$accounts = mysql_query($userQuery, $sqlConnection);
		echo "</br><b>Remove User Account</b></br>";
		echo "</br><form action=\"remove.php\" method=\"post\">";
		echo "<select name=\"removeUser\">";
		while($row = mysql_fetch_array($accounts)) {
			echo "<option>".$row['user']."</option>";
		}
		echo "</select>\n";	
		echo "</br></br><input type=\"submit\" value=\"&nbsp;Remove Account&nbsp;\"/>";
	    echo "</form></br>";
	    mysql_close($sqlConnection);
	}
	
	function removeUser($removeUser) {
		/* I spy a bug */
		$sqlConnection = connectToDatabase();
		mysql_select_db("hpberry", $sqlConnection);
		$count = 0;
		$userQuery = 'SELECT * FROM accounts';
		$accounts = mysql_query($userQuery, $sqlConnection);
		while($row = mysql_fetch_array($accounts)) {
			$count += 1;
		}
		if (1 < $count) {
			$removeUserQuery = 'DELETE FROM accounts WHERE user="'.$removeUser.'"';
			if(mysql_query($removeUserQuery, $sqlConnection))
				echo "</br> > Successfully removed ".$removeUser."'s account.</br>\n";
			else
				echo "</br> > SQL Error: ".mysql_error()."</br>\n";
		} else {
			echo "</br> > Sorry, only (".$count.") accounts remain.</br>\n";
		}
		echo "</br>\n";
	}
	
?>